<template>
    <div>
        <global-tables @changePage="handleChangePage" :total="total" :list="list" @handleAllSelect="handleAllSelect" :loading="loading" :columns="columns" :current="search.pageindex">
            <Form :model="search" :label-width="80">
                <div class="table-top-wrap">
                    <div>
                        <Button v-if="isAddBtn" class="features-btn" @click="handleBtnClick(null,'add')">
                            <Icon type="md-add" size="18" />新建
                        </Button>
                        <Button v-if="isProhibit" class="features-btn btn-auto-m" @click="handleBtnClick(null,'off')">
                            <Icon type="ios-lock-outline" size="17" />停用
                        </Button>
                        <Button v-if="isProhibit" class="features-btn btn-auto-m" @click="handleBtnClick(null,'on')">
                            <Icon type="ios-unlock-outline" size="17" />启用
                        </Button>
                    </div>
                    <div class="table-top-wrap-bottom">
                        <div>
                            <input type="text" class="style-input" @keyup.enter="handleSearch" v-model="search.keyword" placeholder="请输入角色">
                            <i-input style="display:none"></i-input>
                        </div>
                        <div>
                            <Button icon="ios-search" @click="handleSearch" class="search-btn">搜索</Button>
                        </div>
                    </div>
                </div>
            </Form>
        </global-tables>
        <div>
            <Drawer :title="drawerTitle" v-model="isDrawer" width="400" :mask-closable="false" :styles="styles">
                <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100">
                    <Row>
                        <i-col :lg="{ span: 15}">
                            <FormItem label="角色" prop="RoleName">
                                <i-input v-model="formValidate.RoleName" placeholder="请输入角色名称"></i-input>
                            </FormItem>
                        </i-col>
                        <i-col :lg="{ span: 15}">
                            <FormItem label="描述" prop="Remark">
                                <i-input v-model="formValidate.Remark" placeholder="请输入描述"></i-input>
                            </FormItem>
                        </i-col>
                        <i-col :lg="{ span: 24}">
                            <FormItem class="tree-from" >
                                <div class="tree-wrap">
                                    <span>模块</span>
                                    <div class="tree">
                                        <Tree multiple :data="cascaderData" ref="tree" @on-check-change="handleCheckChang" show-checkbox></Tree>
                                    </div>
                                </div>
                            </FormItem>
                        </i-col>
                    </Row>
                    <div class="drawer-footer">
                        <Button style="margin-right: 8px" @click="isDrawer = false">取消</Button>
                        <Button type="primary" @click="handleSubmit('formValidate')">确定</Button>
                    </div>
                </Form>
            </Drawer>
        </div>
    </div>
</template>

<script>
/**
 * 角色列表
 */
import { cyclicRouting, getdate } from "@/util";
import { getModulePermission } from "@/api/user";
import {
    getTablesList,
    getModules,
    addTablesItem,
    dleTablesItem,
    getItemInfo,
    startTablesItem
} from "./service";
import GlobalTables from "@/components/GlobalTables";
export default {
    name: "SystemRole",
    components: {
        GlobalTables
    },
    data() {
        return {
            isProhibit: false,
            isDrawer: false,
            allSelectArr: null,
            Modules: [],
            Buttons: [],
            drawerTitle: "角色新建",
            list: [],
            loading: true,
            ModalTitle: "新建角色",
            total: 0,
            isAddBtn: false,
            isModal: false,
            isEdit: false,
            search: {
                keyword: "",
                pageindex: 1,
                pagesize: 10
            },
            styles: {
                height: "calc(100% - 55px)",
                overflow: "auto",
                paddingBottom: "53px",
                position: "static"
            },
            formValidate: this.initFormValidate(),
            ruleValidate: this.initRuleValidate(),
            cascaderData: [],
            itemId: 0,
            columns: [
                {
                    type: "selection",
                    width: 60,
                    align: "center"
                },
                {
                    title: "角色名称",
                    key: "RoleName"
                },
                {
                    title: "状态",
                    width: 80,
                    key: "Isactivity",
                    render: (h, params) => {
                        const { Isactivity } = params.row;
                        if (Isactivity) {
                            return h("div", [
                                h("Badge", {
                                    props: {
                                        status: "success",
                                        text: "启用"
                                    }
                                })
                            ]);
                        } else {
                            return h("div", [
                                h("Badge", {
                                    props: {
                                        status: "error",
                                        text: "停用"
                                    }
                                })
                            ]);
                        }
                    }
                },
                {
                    title: "创建者",
                    key: "Creator"
                },
                {
                    title: "更新者",
                    key: "Modifier"
                },
                {
                    title: "创建时间",
                    width: 110,
                    key: "CreateTime",
                    render: (h, params) => {
                        if (params.row.CreateTime) {
                            return h("div", [
                                h(
                                    "span",
                                    {
                                        props: {
                                            type: "primary",
                                            size: "small"
                                        }
                                    },
                                    getdate(
                                        new Date(
                                            params.row.CreateTime
                                        ).getTime()
                                    )
                                )
                            ]);
                        }
                    }
                },
                {
                    title: "更新时间",
                    width: 110,
                    key: "LastModifyTime",
                    render: (h, params) => {
                        if (params.row.LastModifyTime) {
                            return h("div", [
                                h(
                                    "span",
                                    {
                                        props: {
                                            type: "primary",
                                            size: "small"
                                        }
                                    },
                                    new Date(
                                        params.row.LastModifyTime
                                    ).getTime() == -28800000
                                        ? ""
                                        : getdate(
                                              new Date(
                                                  params.row.LastModifyTime
                                              ).getTime()
                                          )
                                )
                            ]);
                        }
                    }
                },
                {
                    title: "操作",
                    width: 100,
                    align: "center",
                    render: (h, params) => {
                        const { isEdit } = this;
                        return h("div", [
                            isEdit &&
                                h(
                                    "Button",
                                    {
                                        props: {
                                            type: "primary",
                                            size: "small"
                                        },
                                        style: {
                                            background: "#5ab1ef",
                                            border: "none",
                                            marginRight: "5px"
                                        },
                                        on: {
                                            click: () => {
                                                this.handleBtnClick(
                                                    params.row,
                                                    "edit"
                                                );
                                            }
                                        }
                                    },
                                    "编辑"
                                )
                        ]);
                    }
                }
            ]
        };
    },
    mounted() {
        /* 获取菜单的id */
        cyclicRouting(
            JSON.parse(sessionStorage.getItem("user")).menuList,
            this.$route,
            id => {
                /* 按钮权限请求 */
                getModulePermission({
                    roleid: JSON.parse(sessionStorage.getItem("user")).roleid,
                    moduleid: id
                }).then(res => {
                    /* 按钮权限赋值 */
                    for (let item in res.data) {
                        if (res.data[item].name == "add") {
                            /* 如果用户权限有新建 */
                            this.setAddButton();
                        } else if (res.data[item].name == "onoff") {
                            this.isProhibit = true;
                        } else if (res.data[item].name == "edit") {
                            this.isEdit = true;
                        }
                    }
                    /* 列表请求 */
                    this.getTablesListData();
                });
            }
        );
    },
    methods: {
        /* 表格分页方法 */
        handleChangePage(type, page) {
            this.loading = true;
            if (type == "page") {
                this.search.pageindex = page;
                this.getTablesListData();
            } else {
                this.search.pagesize = page;
                this.getTablesListData();
            }
        },
        /* 关闭对话框 */
        handleClose() {
            this.isModal = false;
        },
        /* 多选 */
        handleAllSelect(list) {
            let arr = [];
            for (let item in list) {
                arr.push(list[item].ID);
                arr.join(",");
            }
            arr = arr.join(",");
            this.allSelectArr = arr;
        },
        /* 表格查询 */
        handleSearch() {
            this.loading = true;
            this.getTablesListData();
        },
        /* 对话框提交 */
        handleSubmit(name) {
            const { formValidate, Modules, Buttons } = this;
            this.$refs[name].validate(valid => {
                if (valid) {
                    if (Modules != "") {
                        const data = {
                            RoleName: formValidate.RoleName,
                            Remark: formValidate.Remark,
                            Modules: Modules.join(","),
                            Buttons: Buttons.join(","),
                            ID: this.itemId
                        };
                        addTablesItem(data).then(res => {
                            if (res.state == "success") {
                                this.$Message.success("操作成功");
                                this.loading = true;
                                this.isDrawer = false;
                                this.handleClose();
                                this.getTablesListData();
                            } else {
                                this.$Message.error(res.message);
                            }
                        });
                    } else {
                        this.$Message.error("请选择模块");
                    }
                }
            });
        },
        /* 表格数据请求 */
        getTablesListData() {
            const data = this.search;
            getTablesList(data).then(res => {
                this.list = res.data.rows;
                this.loading = false;
                this.total = res.data.records;
            });
        },
        /* 新建按钮显示 */
        setAddButton() {
            this.isAddBtn = true;
        },
        /* 对话框操作点击 */
        handleBtnClick(item, type) {
            if (type == "edit" || type == "add") {
                this.drawerTitle = "新建角色";
                this.isDrawer = true;
                this.itemId = 0;
                if (type == "edit") {
                    this.drawerTitle = "修改角色";
                    this.isDrawer = true;
                    this.type = "edit";
                    this.itemId = item.ID;
                    /* 获取一条的id */
                    getItemInfo({
                        id: item.ID
                    }).then(res => {
                        // 赋值给表单;
                        this.formValidate = {
                            RoleName: res.data.RoleName,
                            Remark: res.data.Remark
                        };
                        this.setModules(res.data.Authorize, true);
                    });
                } else {
                    this.ModalTitle = "新建角色";
                    this.itemId = 0;
                    this.isModal = true;
                    this.formValidate = this.initFormValidate();
                    this.Buttons = [];
                    this.Modules = [];
                    // 获取模块
                    getModules().then(res => {
                        this.setModules(res.data);
                    });
                }
            } else if (type === "off") {
                if (this.allSelectArr) {
                    this.$Modal.confirm({
                        title: `你确定要停用吗`,
                        onOk: () => {
                            dleTablesItem({
                                ids: this.allSelectArr,
                                UID: JSON.parse(sessionStorage.getItem("user"))
                                    .uid
                            }).then(res => {
                                if (res.state == "success") {
                                    this.$Message.success(res.message);
                                } else {
                                    this.$Message.error(res.message);
                                }
                                this.getTablesListData();
                            });
                        },
                        onCancel: () => {
                            this.$Message.info("取消成功");
                        }
                    });
                } else {
                    this.$Message.error("请先选择需要操作的记录");
                }
            } else if (type === "on") {
                if (this.allSelectArr) {
                    this.$Modal.confirm({
                        title: `你确定要启用吗`,
                        onOk: () => {
                            startTablesItem({
                                ids: this.allSelectArr,
                                UID: JSON.parse(sessionStorage.getItem("user"))
                                    .uid
                            }).then(res => {
                                if (res.state == "success") {
                                    this.$Message.success(res.message);
                                } else {
                                    this.$Message.error(res.message);
                                }
                                this.getTablesListData();
                            });
                        },
                        onCancel: () => {
                            this.$Message.info("取消成功");
                        }
                    });
                } else {
                    this.$Message.error("请先选择需要操作的记录");
                }
            }
        },
        /* 树点击 */
        handleCheckChang() {
            let arr = this.$refs.tree.getCheckedAndIndeterminateNodes()
            this.Modules = [];
            this.Buttons = [];
            for (let item in arr) {
                if (arr[item].Type == 1) {
                    this.Modules.push(arr[item].ID);
                } else {
                    this.Buttons.push(arr[item].ID);
                }
            }
        },
        /* 表单数据 */
        initFormValidate() {
            return {
                RoleName: "",
                Remark: ""
            };
        },
        /* 设置模块 */
        setModules(list) {
            list.forEach(item => {
                item.title = item.ModuleTitle;
                item.checked = item.ParentID == 0 ? false : item.Checked;
                item.expand = item.checked ? true : false;
                if (item.Checked) {
                    if (item.Type == 1) {
                        this.Modules.push(item.ID);
                    } else {
                        this.Buttons.push(item.ID);
                    }
                }
                if (item.Childs && Array.isArray(item.Childs)) {
                    item["children"] = item.Childs;
                    this.setModules(item.children);
                }
            });
            this.cascaderData = list;
        },
        /* 表单校验 */
        initRuleValidate() {
            return {
                RealName: [
                    {
                        required: true,
                        message: "请输入角色名称",
                        trigger: "change"
                    }
                ]
            };
        }
    }
};
</script>

<style lang="less" scoped>
.tree-wrap {
    position: relative;
    span {
        position: absolute;
        top: 0;
        left: -35px;
    }
}
.drawer-footer {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    background: #fff;
}

</style>

